<template>
  <div class="chat-info">
    <div class="chat-data">
      <div class="chat-id">
        <i
          class="V7_iconfont V7_iconV7tubiao_lianluojilu"
          style="color: #008bee"
        ></i>
        <span class="label">会话ID:</span>
        <p class="id">
          {{ webchatInfo._id }}
        </p>
      </div>
      <div
        class="info"
        v-functions="['qc_webchat_session_query_agent']"
        v-if="infoType === 'result'"
      >
        <span class="label">处理座席</span>
        <span class="value">{{ detailData["agentName"] }}</span>
      </div>
      <div class="info" v-if="infoType !== 'result'">
        <span class="label">处理座席</span>
        <span class="value">{{ detailData["agentName"] }}</span>
      </div>
      <div
        v-for="item in chatInfo"
        :key="item.prop"
        class="info"
        v-show="item.prop !== 'agentName'"
      >
        <span class="label">{{ item.label }}</span>
        <span class="value" v-if="item.prop === 'agentClaimTimestamp'">{{
          detailData[item.prop] | filterTimestamp
        }}</span>
        <span class="value" v-else>{{ detailData[item.prop] }}</span>
      </div>
    </div>
    <div class="chat-content">
      <div class="chat-content-title">
        <el-tabs v-model="activeName" @tab-click="handleTabChange">
          <el-tab-pane :label="'会话'" name="chatNum"></el-tab-pane>
          <!-- <el-tab-pane
          :label="'关联工单 (' + 0 + ')'"
          name="relateWork"
        ></el-tab-pane> -->
        </el-tabs>
      </div>
      <div class="chat-box">
        <webchatContentBox
          :importType="'dataCenter'"
          :webchatInfo="webchatInfo"
          :chatType="'webchat_session'"
          :moduleType="'quality_score'"
          class="webchatContent fl"
          ref="webchatContentBox"
        ></webchatContentBox>
      </div>
    </div>
  </div>
</template>
<script lang="ts">
import { Component, Vue, Watch, Prop } from 'vue-property-decorator'
import configTable from '@/components/globalTool/resizeTable/index.vue'
import webchatDataSummary from '@/views/dataCenter/webchatData/webchatDataSummary.vue'
import { WebchatModule } from '@/store/modules/webchat'
import webchatContentBox from '@/views/webchat/webchatContentBox.vue'
import { formatStamp, commonAction, millsToDate } from '@/utils/common'
@Component({
  name: 'chatInfo',
  components: {
    configTable,
    webchatDataSummary,
    webchatContentBox
  },
  filters: {
    filterTimestamp (value: string) {
      if (value) {
        return formatStamp(value);
      } else {
        return value;
      }
    }
  }
})
export default class ChatInfo extends Vue {
  private handleTabChange () {
    // 11
  }

  // ----------------传入属性-----------------------
  [x: string]: any

  @Prop({ default: '' }) public sessionId!: string; // 会话ID

  @Prop({ default: '' }) public scoringId!: string; // 评分ID

  @Prop({ default: '' }) public infoType!: string; // 操作类型 result 结果查询
  @Prop({ default: '' }) public visitorId!: string; // 会话ID
  // ----------------内部属性-----------------------

  private detailData: any = {}

  private chatInfo: any = [
    {
      label: '处理座席',
      prop: 'agentName'
    },
    {
      label: '来源渠道',
      prop: 'accessName'
    },
    {
      label: '满意度',
      prop: 'satisfactionName'
    },
    {
      label: '结束类型',
      prop: 'finishReason'
    },
    {
      label: '城市',
      prop: 'area'
    },
    {
      label: '会话领取时间',
      prop: 'agentClaimTimestamp'
    },
    {
      label: '会话结束时间',
      prop: 'endTime'
    },
    {
      label: '会话时长',
      prop: 'sesssionTimeLength'
    },
    {
      label: '首次响应时间',
      prop: 'agentFirstReplyTime'
    },
    {
      label: '首次响应时长',
      prop: 'agentFirstReplyLength'
    }
  ]

  private activeName: any = 'chatNum'
  // ----------------计算属性-----------------------
  get webchatInfo () {
    if (this.sessionId) {
      return this.$store.state.webchat.webchatInfo[this.sessionId] || {}
    } else {
      return {}
    }
  }
  // ----------------监听方法-----------------------

  @Watch('sessionId', { immediate: true })
  private sessionIdChange (newId: any) {
    if (newId) {
      this.initData();
      this.getSessionDataByVisitorId(this.scoringId);
    }
  }
  // ----------------调用方法-----------------------

  private initData () { // 详情
    this.isShowDrawer = true
    const visitorId = this.visitorId;
    const sessionId = this.sessionId;
    let url = '/im-center/action/webchat/queryChatInfoById'
    if (this.activeName === 'leave') {
      url = '/im-center/action/webchat/queryLeaveSessionInfoById'
    }
    const chatInfoActionData = { url, method: 'POST', data: { visitorId, _id: sessionId } }
    const serveTimeActionData = { url: '/im-center/action/webchat/getServerTimeDiff', method: 'POST', data: { localTimestamp: new Date().getTime() } }
    const queryServeTime = WebchatModule.webchatCommonAction(serveTimeActionData) // 获取服务器时间
    const queryChatInfoById = WebchatModule.queryChatInfoById(chatInfoActionData) // 获取会话详情
    Promise.all([queryChatInfoById, queryServeTime]).then(([chatInfo, serveTime]: any) => {
      if (chatInfo && serveTime && serveTime.serverTime && chatInfo.chatSession) {
        const messageHistoryData = { // 获取消息历史参数
          visitorId,
          dateTime:
            serveTime.serverTime,
          limit: 20,
          _id: sessionId,
          isNewSession: true,
          webchatType: 'webchatDateCenter',
          sessionId: chatInfo.chatSession._id
        }
        const messageHistoryActionData = { url: '/im-center/action/webchat/queryHistory', method: 'POST', data: messageHistoryData }
        WebchatModule.queryWebchatHistory(messageHistoryActionData).then(res => { // 获取会话历史
          if (res && res.messageList) {
            (this.$refs as any).webchatContentBox.scrollToBottom({ scrollName: 'webchatContentBox', warpName: 'chatMsgBox' })
            this.$bus.$emit('initWebchatDataCenter', { chatSession: chatInfo.chatSession, processInfo: chatInfo.scheduleHistory, visitorInfo: chatInfo.visitorInfo || {} })
          }
        })
      }
      // this.webchatInfo = chatInfo.chatSession;
    })
  }

  private getSessionDataByVisitorId (id: string) {
    const params = {
      url: '/im-center/action/quality/queryQualityRecord',
      method: 'POST',
      data: {
        qualitySessionId: id
      }
    }
    commonAction(params).then(res => {
      if (res.success) {
        const channelList = this.$store.state.common.publicCache.channelList || []
        const result: any = res.data;
        const item = result.data || {};
        item.scoringID = result._id;
        item.applyQualityTime = result.applyQualityTime;
        const accessObj = channelList.find((channelItem: any) => { // 接入号
          return channelItem.accessId === item.accessId
        })
        item.accessName = accessObj ? accessObj.name : '--'
        const agentObj = this.$store.state.common.publicCache.userListObj[item.userId] // 座席
        item.agentName = agentObj ? agentObj.name : '--'
        const queueObj = this.$store.state.common.publicCache.queueListObj[item.toPeer] // 技能组
        item.queueName = queueObj ? queueObj.name : '--'
        item.satisfactionName = item.satisfactionData && item.satisfactionData.satisfactionName ? item.satisfactionData.satisfactionName : '' // 满意度名称
        if (item.satisfactionData && item.satisfactionData.satisfactionReason.length > 0) { // 满意度标签
          item.satisfactionReason = ''
          item.satisfactionData.satisfactionReason.forEach(reasonItem => {
            item.satisfactionReason += reasonItem + '/'
          })
          item.satisfactionReason = item.satisfactionReason.substring(0, item.satisfactionReason.length - 1)
        } else {
          item.satisfactionReason = '--'
        }
        const sessionTagsInfoObj = {}
        if (item.sessionTagsInfo) {
          item.sessionTagsInfo.forEach(tagInfoItem => {
            sessionTagsInfoObj[tagInfoItem._id] = tagInfoItem
          })
        }
        if (item.sessionTags && item.sessionTags.length > 0) {
          const arr: any = []
          item.sessionTags.forEach((sessionTagItem: any) => {
            if (this.webchatLabelTreeObj[sessionTagItem]) {
              arr.push(this.webchatLabelTreeObj[sessionTagItem])
            } else {
              arr.push(sessionTagsInfoObj[sessionTagItem])
            }
          })
          item.sessionTags = arr
        } else {
          item.sessionTags = []
        }
        item.satisfactionProposal = item.satisfactionData && item.satisfactionData.satisfactionProposal ? item.satisfactionData.satisfactionProposal : '' // 满意度备注
        if (item.manualTimestamp && item.agentFirstReplyTimestamp) {
          item.agentFirstReplyLength = millsToDate(item.agentFirstReplyTimestamp - (item.manualTimestamp || item.createTimestamp)) // 首次响应时长
        } else {
          item.agentFirstReplyLength = '--'
        }

        item.sesssionTimeLength = item.sesssionTimeLength ? millsToDate(item.sesssionTimeLength) : '--' // 对话时长
        this.$set(this, 'detailData', item);
      }
    })
  }
  // ----------------生命周期-----------------------
}
</script>
<style lang="stylus" scoped>
.webchatContent
  height 100%
  width 100%
.chat-info
  width 100%
  height 100%
  .chat-data
    width 100%
    height 45%
    overflow-y: scroll
    border-bottom 1px solid #E7E9ED
    padding 20px 24px
    .chat-id
      background #E5F3FD
      border-radius 4px
      padding 12px
      margin-bottom 20px
      .label
        font-weight 600
        color #303753
        margin-left 6px
      .id
        width 100%
        overflow hidden
        text-overflow ellipsis
        word-break keep-all
        white-space nowrap
        font-weight 600
        color #686E84
        margin-top 10px
  .info
    display flex
    justify-content space-between
    margin-bottom 10px
    .label
      width 72px
      color #767E91
    .value
      flex 1
      color #303753
      text-align right
.chat-content
  padding 0
  height 55%
  .chat-box
    height: calc(100% - 55px)
  .chat-content-title
    padding 0px 10px 0px
    height: 55px
</style>
